function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return (r[2]);
    return null; //返回参数值
}

var orderNum = getUrlParam("orderNum");
var gateway = getUrlParam("gateway");
var payerId = getUrlParam("payerId");
var bindId = null;
var accessBindId = null;
var orderIp = null;
var phone = null;
var token = null;
var time = 0;
var timer = null;
var payType = 'alipay';
var amount = "0";


$(function () {
    payType = getUrlParam("type");
    amount = getUrlParam("amount");
    if (payType == 'wechat' || payType == 'alipay') {
        document.getElementById("select-card").style.display = "none";
        var btn = document.getElementById('confirm-btn');
        btn.style.display = 'none';
        mui.trigger(btn, 'tap');
    } else {
        document.getElementById("select-card").style.display = "block";
        $.getJSON("/thmlfApi/avs/pay/getpayerallbind?gateway=hkpay" + "&payerId=" + payerId + "&_d=" + Date.parse(new Date()), null, function (r) {
            if (r.code == 200) {
                $.each(r.result, function (index, data) {
                    var cardType = data.cardType == "X" ? "信用卡" : "借记卡";
                    var item = '<div class="mui-input-row mui-radio mui-left bind-card-item" data-token="' + data.token + '" data-access-bind-id="' + data.accessBindId + '" data-bindid="' + data.bindId + '" data-phone="' + data.phone + '">' +
                        '<label>' + data.cardName + '&nbsp;&nbsp;' + cardType + '&nbsp;&nbsp;' + data.holdName + '&nbsp;&nbsp;' + '尾号' + data.lastFourNum + '</label>' +
                        '<input name="card" type="radio">' +
                        '</div>';
                    $(".add-new-card").before(item);
                });
                bindChoose();
            }
        });
    }
    $("#addBindCard").click(function () {
        bindId = null;
        window.location.href = "card-manage.html";
    });
});

function wechatPay() {
    mui('.confirm-btn').button("loading");
    $('.mui-popup-backdrop').css('display', 'block');
    $.ajax({
        url: "/thmlfApi/avs/hkpay/createWechatPayUrl",
        type: "POST",
        dataType: "JSON",
        data: {
            "cashBindId": accessBindId,
            "orderNum": orderNum,
            "payerId": payerId
        },
        success: function (r) {
            $('.mui-popup-backdrop').css('display', 'none');
            mui('.confirm-btn').button("reset");
            if (r.code == 200) {
                $('.qr_img').attr('src', 'data:image/png;base64,' + r.result);
                var qr = $('.wechat');
                var mask = mui.createMask(function () {
                    qr.css('display', 'none');
                });
                mask.show();
                $('.money').text(amount);
                qr.css('display', 'block');
            } else if (r.code == 101) {
                goToMerReg("商户尚未注册，是否前往注册？");
            } else if (r.code == 102) {
                goToMerReg("商户尚未提交资料，是否前往提交资料？");
            } else {
                mui.toast(r.message);
            }
        },
        error: function (e) {
            $('.mui-popup-backdrop').css('display', 'none');
            console.error("request error ", e);
            mui('.confirm-btn').button("reset");
            mui.toast("服务器繁忙");
        }
    });
}

// 关闭
mui(document.body).on('tap', '.close', function () {
    // $(".qr").css('display','none');
    window.history.back();
});

// 确认信息
mui(document.body).on('tap', '.confirm-btn', function () {
    var that = mui(this);
    console.log("data", accessBindId, token);
    if (accessBindId == null && payType != 'wechat' && payType != 'alipay') {
        mui.toast("请选择银行卡");
        return;
    }
    if (payType == 'wechat') {
        wechatPay();
        return;
    }
    that.button('loading');
    $.ajax({
        url: "/thmlfApi/avs/hkpay/createorder",
        data: {
            "payerId": payerId,
            "cashBindId": accessBindId,
            "orderNum": orderNum,
            "type": payType
        },
        dataType: "JSON",
        type: "POST",
        success: function (r) {
            that.button('reset');
            if (r.code == 200) {
                if (r.result.type == 'qr') {
                    // 二维码
                    $('.qr_img').attr('src', 'data:image/png;base64,' + r.result.qrUrl);
                    var qr = null;
                    if (payType == 'alipay') {
                        qr = $('.alipay');
                    } else {
                        qr = $('.wechat');
                    }
                    var mask = mui.createMask(function () {
                        qr.css('display', 'none');
                    });
                    mask.show();
                    $('.money').text(amount);
                    qr.css('display', 'block');
                } else if (r.result.type == 'html') {
                    // 网页
                    // document.getElementById('from-hidden').innerHTML = r.result.html;
                    // document.all.pay_form.submit();
                    $("body").append(r.result.html);
                }
            } else if (r.code == 101) {
                goToMerReg("商户尚未注册，是否前往注册？");
            } else if (r.code == 102) {
                goToMerReg("商户尚未提交资料，是否前往提交资料？");
            } else {
                mui.alert(r.message);
            }
        },
        error: function (e) {
            that.button('reset');
            console.error("request error", e);
            mui.toast("服务器繁忙");
        }
    })
});

// 前往商户注册
function goToMerReg(msg) {
    var btnArray = ['否', '是'];
    mui.confirm(msg, '提示', btnArray, function (e) {
        if (e.index == 1) {
            window.location.href = './merchant/index.html';
        }
    })
}


// 验证码计时器
function times() {
    if (time > 0) {
        $("#sms_code_btn").text(time + 's');
        time--;
    } else {
        clearInterval(timer);
        time = 0;
        $("#sms_code_btn").text('获取');
    }
}

// 选择银行卡
function bindChoose() {
    $(".bind-card-item").click(function () {
        bindId = $(this).attr("data-bindid");
        phone = $(this).attr("data-phone");
        token = $(this).attr("data-token");
        accessBindId = $(this).attr("data-access-bind-id");
    })
}